#include <delete_timer.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>

#include <flache_debug.h>

/***************************************************
 * if the file exists, remove it, otherwise, don't bother
 **************************************************/
static int rm( char* path )
{
    int result = 0;
    struct stat st;

    if ( 0 == stat(path, &st) )
    {
        char* rm = "rm -f ";
        int length = strlen( rm ) + strlen( path ) + 3;
        char* cmd = (char*)malloc( length );
        sprintf( cmd, "%s\"%s\"", rm, path );
        result = system( cmd );
        free( cmd );
    }

    return result;
}

/*************************************************
 * main timer thread loop
 *************************************************/
void *delete_timer_start( void* thread_info )
{
    struct timer_thread_info* info = (struct timer_thread_info*) thread_info; 
    struct file_entry_list_t* list = info->list;
    struct flache_vol_t* volume = info->volume;
    int* cancel = info->cancel;

    // loop while the thread hasn't been cancelled.
    while( FALSE == *cancel )
    {
        sleep( DEFAULT_TIMER_SLEEP );

        // check again, just to catch it before it
        // processes the list again
        if ( TRUE == *cancel )
            break;

        pthread_mutex_lock( &volume->write_lock );

        lock_list( list );

        int i;
        for ( i = list->file_count - 1; i >= 0; i-- )
        {   
            
            lock_entry( list->entries[i] );

            struct file_entry_t* file = list->entries[i];
            /*write_output2( "del_timer: file lock", file->path );
            if ( !file->dirty )
            {
                write_output2( "del_timer: not dirty: ", file->path );
                char msg[2000];
                int val = (int)((time(NULL) - file->time_released) - DEFAULT_TIME_TO_LIVE);
                sprintf( msg, "del_timer: val: %d; released: %d", val, (int)file->time_released );
                write_output( msg );
            } */

            if ( file->handle_count == 0 &&
                 !file->dirty && 
                 (time(NULL) - file->time_released) - DEFAULT_TIME_TO_LIVE > 0 )
            {
                // try to delete, free if successful
                if ( 0 == rm( file->flash_path ) )
                {
                    if ( DEBUG )
                        write_output2( "reclaimed: ", file->path );

                    remove_file( list, file );
                    _free_entry( file );
                }
                else // if we couldn't delete it, then re-queue
                {
                    file->time_released = time(NULL);
                    unlock_entry( file );
                }
            }
            else
                unlock_entry( file );
        }

        unlock_list( list );
        
        pthread_mutex_unlock( &volume->write_lock );
    }

    return NULL;
}

